package com.zsck.zsgy.ui.guide

import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zsck.commonbase.util.StatusUtils
import com.zsck.commonbase.widget.DialogManager
import com.zsck.zsgy.R
import com.zsck.zsgy.base.BaseActivity
import com.zsck.zsgy.databinding.ActivitySplashLayoutBinding
import com.zsck.zsgy.ui.guide.bean.KeyListBean
import com.zsck.zsgy.ui.guide.bean.VersionListBean
import com.zsck.zsgy.ui.main.MainActivity
import com.zsck.zsgy.util.*

class SplashActivity : BaseActivity<SplashViewModel, ActivitySplashLayoutBinding>() {


    var LOCATIONINIT: Boolean = false
    var KEYINIT: Boolean = false
    override fun layoutId(): Int {
        return R.layout.activity_splash_layout
    }

    private var isFirst: Boolean = false
    override fun initView() {
        super.initView()
        isFirst = PrefserHelper.isFirst()
        if (!isFirst) {
            startActivity(GuideActivity::class.java)
            finish()
            return
        }
    }

    private var versionListBean: List<VersionListBean>? = null
    private var keyList: KeyListBean? = null
    override fun initData() {
        binding.splashViewModel = viewModel
        StatusUtils.setSystemStatus(this, true, false)
        var keyListBean: KeyListBean? = PrefserHelper.getKeyList()
        viewModel.postGetVersion("dictionary")
        viewModel.splashViewModel.observe(this, Observer {
            var version: String = PrefserHelper.getVersion()
            versionListBean = it
            if (keyListBean.isNotNull()) {
                if (it.size > 0) {
                    if (!version.equals(it[0].version)) {
                        PrefserHelper.saveVersion(it[0].version)
                        keyList()
                    } else {
                        KEYINIT = true
                        sendLiveEventDataDelay(LiveDataEvent(SPLASH_VALUE))
                    }
                } else {
                    KEYINIT = true
                    sendLiveEventDataDelay(LiveDataEvent(SPLASH_VALUE))
                }
            } else {
                keyList()
            }


        })
        viewModel.errorLiveData.observe(this, Observer {
            dismissDialog()
            KEYINIT = true
            sendLiveEventDataDelay(LiveDataEvent(SPLASH_VALUE))
        })

        checkLocationPermission()

    }

    /**
     * 检查是否有定位权限
     */
    private fun checkLocationPermission() {

        if (PermissionUtil.hasPermission(this, PermissionUtil.LOCATION)) {
            LOCATIONINIT = true
            initLocation()
        } else {
            PermissionUtil.requestPermission(
                this,
                PermissionUtil.LOCATION,
                PermissionUtil.REQUEST_LOCATION
            )
        }
    }

    /**
     * 请求定位权限
     */
    private fun initLocation() {
        var location = LocationUtils.getInstance(this)
        location.getAddress()
        LogUtils.e("位置信息： 开始请求" )

    }

    /**
     * 获取值集
     */
    private fun keyList() {
        viewModel.keyList("longRent")
        viewModel.splashKeyModel.observe(this, Observer {
            keyList = it
            KEYINIT = true
            PrefserHelper.saveKeyList(it)
            sendLiveEventDataDelay(LiveDataEvent(SPLASH_VALUE))
        })
        viewModel.errorLiveData.observe(this, Observer {
            KEYINIT = true
            sendLiveEventDataDelay(LiveDataEvent(SPLASH_VALUE))
        })
    }

    /**
     * 延时跳转主页
     */
    override fun initLiveData() {
        LiveEventBus.get(LiveDataEvent::class.java).observe(this, { liveDataEvent ->
            if (liveDataEvent.event == SPLASH_VALUE && LOCATIONINIT && KEYINIT) {
                startActivity(MainActivity::class.java)
                finish()
            } else if (liveDataEvent.event == SPLASH_LOCATION) {
                LOCATIONINIT = true
                sendLiveEventData(LiveDataEvent(SPLASH_VALUE))
            } else if (liveDataEvent.event == LOCATION) {
                LOCATIONINIT = true
                LocationUtils.getInstance(this).removeLocationUpdatesListener()
            } else if (liveDataEvent.event == LOCATIONINFO) {
                LOCATIONINIT = true
                LocationUtils.getInstance(this).removeLocationUpdatesListener()
                sendLiveEventData(LiveDataEvent(SPLASH_VALUE))
            }
        })
    }


    /**
     * 重新请求权限
     */
    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        super.onPermissionsDenied(requestCode, perms)
        LogUtils.e("请求失败------------------")
        val dialogManager = DialogManager(
            getString(R.string.tips),
            getString(R.string.confirm),
            getString(R.string.permission_tips),
            getString(R.string.cancel)
        )
        dialogManager.setOnSureClick(object : DialogManager.onSureClick {
            override fun onSureClick() {
                val localIntent = Intent()
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                if (Build.VERSION.SDK_INT >= 9) { //系统8.0以上的
                    localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                    localIntent.data = Uri.fromParts("package", packageName, null)
                } else if (Build.VERSION.SDK_INT <= 8) { //系统8.0以下的
                    localIntent.action = Intent.ACTION_VIEW
                    localIntent.setClassName(
                        "com.android.settings",
                        "com.android.settings.InstalledAppDetails"
                    )
                    localIntent.putExtra(
                        "com.android.settings.ApplicationPkgName",
                        packageName
                    )
                }
                startActivityForResult(localIntent, OPEN_SET)
                dialogManager.dismiss()
            }

            override fun onCancleClick() {}
        })
        dialogManager.show(supportFragmentManager, "permission")

    }


    /**
     * 权限请求成功
     */
    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        LOCATIONINIT = true
        initLocation()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == OPEN_SET) {
            if (PermissionUtil.hasPermission(this, PermissionUtil.LOCATION)) {
                LOCATIONINIT = true
                initLocation()
            } else {
                LOCATIONINIT = true
                sendLiveEventDataDelay(LiveDataEvent(SPLASH_VALUE))
            }
        }
    }
}